<?php
namespace User\Controller;

use Common\Controller\MemberbaseController;
use Common\Log\TypeLog;
use Portal\Lib\TagLib\Portal;
use Portal\Model\PostsModel;

class ProfileController extends MemberbaseController {
	
	function _initialize(){
		parent::_initialize();
	}
	
    // 编辑用户资料
	public function edit() {
	    $user = $this->user;
	    if ($user['city_id'] > 0) {
	        $city_name = M('area')->where(['id' => $user['city_id']])->field('areaname')->find();
	        $user['city_name'] = $city_name['areaname'];
        }
        if ($user['mobile']) {
            $user['short_mobile'] = substr_replace($user['mobile'],'****',3,4);
        }
		$this->assign($user);
    	$this->display();
    }
    
    // 编辑用户资料提交
    public function edit_post()
    {
        if (IS_POST) {
            $_POST['id'] = $this->userid;
            if ($this->users_model->field('id,user_nicename,marry,birthday,city_id,signature,position,company')->create() !== false) {
                if ($this->users_model->save() !== false) {
                    $this->user = $this->users_model->find($this->userid);
                    sp_update_current_user($this->user);
                    $this->success("保存成功！");
                } else {
                    $this->error("保存失败！");
                }
            } else {
                $this->error($this->users_model->getError());
            }
        }
    }

    // 修改密码提交
    public function password_post() {
    	if (IS_POST) {
    	    // 验证手机验证码
            $mobile     = I('mobile');
            $sms_code   = I('sms_code');
            if(!sp_check_sms_code($mobile, $sms_code)){
                $this->error("手机验证码错误！");
            }

            // 绑定手机操作
            $bind_mobile = I('bind_mobile');
            if ($bind_mobile) {
                $has_mobile_user = $this->users_model->where(array('mobile' => $mobile))->find();
                if ($has_mobile_user) {
                    $this->error('该手机号已绑定');
                }
            }

            $uid  = sp_get_current_userid();
            $user = $this->users_model->where(array('id' => $uid))->find();

            $old_password = I('post.old_password');
            // 原来有密码
            if ($user['user_pass'] && $user['mobile']) {
                if (!sp_compare_password($old_password, $user['user_pass'])) {
                    $this->error("原始密码不正确！");
                }
            }

            $password   = I('post.password');
            $repassword = I('post.repassword');
            if (empty($password)) {
                $this->error("新密码不能为空！");
            }
            if ($password != $repassword) {
                $this->error("新密码和确认密码不同");
            }

            // 修改数据
            $data               = array();
            $data['user_pass']  = sp_password($password);
            $data['id']         = $uid;
            $data['mobile']     = $user['mobile'] ?: $mobile;
            $re                 = $this->users_model->save($data);
            if ($re !== false) {
                if ($bind_mobile) {
                    $msg = '绑定成功';
                } else {
                    $msg = "修改成功";
                }
                $new_user_info = $this->users_model->where(array('id' => $uid))->find();
                sp_update_current_user($new_user_info);
                $this->success($msg);
            } else {
                if ($bind_mobile) {
                    $msg = '绑定失败';
                } else {
                    $msg = "修改失败";
                }
                $this->error($msg);
            }
    	}
    }
    
    // 第三方账号绑定
    public function bang(){
    	$oauth_user_model=M("OauthUser");
    	$uid=sp_get_current_userid();
    	$oauths=$oauth_user_model->where(array("uid"=>$uid))->select();
    	$new_oauths=array();
    	foreach ($oauths as $oa){
    		$new_oauths[strtolower($oa['from'])]=$oa;
    	}
    	$this->assign("oauths",$new_oauths);
    	$this->display();
    }
    
    // 用户头像编辑
    public function avatar(){
		$this->assign($this->user);
    	$this->display();
    }
    
    // 用户头像上传
    public function avatar_upload(){
    	$config=array(
			'rootPath'      => './'.C("UPLOADPATH"),
			'savePath'      => './avatar/',
			'maxSize'       => 512000,//500K
			'saveName'      => array('uniqid',''),
			'exts'          => array('jpg', 'png', 'jpeg'),
			'autoSub'       => false,
    	);
    	$upload = new \Think\Upload($config,'Local');//先在本地裁剪
    	$info=$upload->upload();
    	//开始上传
    	if ($info) {
    	//上传成功
    	//写入附件数据库信息
    		$first=array_shift($info);
    		$file=$first['savename'];
    		session('avatar',$file);
    		$this->ajaxReturn(sp_ajax_return(array("file"=>$file),"上传成功！",1),"AJAX_UPLOAD");
    	} else {
    		//上传失败，返回错误
    		$this->ajaxReturn(sp_ajax_return(array(),$upload->getError(),0),"AJAX_UPLOAD");
    	}
    }
    
    // 用户头像裁剪
    public function avatar_update(){
        $session_avatar=session('avatar');
    	if(!empty($session_avatar)){
    		$targ_w = I('post.w',0,'intval');
    		$targ_h = I('post.h',0,'intval');
    		$x = I('post.x',0,'intval');
    		$y = I('post.y',0,'intval');

    		$avatar=$session_avatar;
    		$avatar_dir=C("UPLOADPATH")."avatar/";
    		
    		$avatar_path=$avatar_dir.$avatar;
    		$avatar = time().$avatar;
    		$new_path = $avatar_dir.$avatar;
    		
    		$image = new \Think\Image();
    		$image->open($avatar_path);
    		$image->crop($targ_w, $targ_h,$x,$y);
    		$image->save($new_path);

    		unlink($avatar_path);
    		
    		$result=true;
    		
    		$file_upload_type=C('FILE_UPLOAD_TYPE');
    		if($file_upload_type=='Qiniu'){
    		    $upload = new \Think\Upload();
    		    $file=array('savepath'=>'','savename'=>'avatar/'.$avatar,'tmp_name'=>$new_path);
    		    $result=$upload->getUploader()->save($file);
    		}
    		if($result===true){
    		    $userid=sp_get_current_userid();
    		    $result=$this->users_model->where(array("id"=>$userid))->save(array("avatar"=>'avatar/'.$avatar));
    		    session('user.avatar','avatar/'.$avatar);
    		    if($result){
    		        $this->success(json_encode($avatar));
    		    }else{
    		        $this->error("头像更新失败！");
    		    }
    		}else{
    		    $this->error("头像保存失败！");
    		}
    		
    	}
    }
    
    // 保存用户头像
    public function do_avatar() {
		$imgurl=I('post.imgurl');
		//去'/'
		$imgurl=str_replace('/','',$imgurl);
		$old_img=$this->user['avatar'];
		$this->user['avatar']=$imgurl;
		$res=$this->users_model->where(array("id"=>$this->userid))->save($this->user);		
		if($res){
			//更新session
			session('user',$this->user);
			//删除旧头像
			sp_delete_avatar($old_img);
		}else{
			$this->user['avatar']=$old_img;
			//删除新头像
			sp_delete_avatar($imgurl);
		}
		$this->ajaxReturn($res);
	}

	// 编辑基础信息
    public function edit_baseinfo()
    {
        $tab_index = I('tab_index');
        if (!$tab_index) {
            $tab_index = 1;
        }
        $this->assign('tab_index', $tab_index);

        $this->assign('area', json_encode(getArea(2)));
        $user = $this->user;
        if ($user['mobile']) {
            $user['short_mobile'] = substr_replace($user['mobile'],'****',3,4);
        }
        $this->assign($user);
        if ($this->user['city_id'] > 0) {
            $path = getAreaParentPath($this->user['city_id'], getArea(2));
            $path = $path ? $path : '';
            $this->assign('path', json_encode($path));
        }
        $this->display();
	}

	// 新的保存用户头像，简单粗暴
    public function save_user_avatar()
    {
        $pre        = './data/upload/avatar/';
        $user_id    = sp_get_current_userid();
        $dataUrl    = I('data_url');

        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $dataUrl, $result)) {
            $ext        = $result[2];
            $file_path  = $pre . $user_id . '.' . $ext;

            if (file_exists($file_path)) {
                unlink($file_path);
            }

            file_put_contents($file_path, base64_decode(str_replace($result[1], '', $dataUrl)));

            // 上传至阿里云
            if (C('UPLOAD_ALIYUN')) {
                $result = upload_img_aliyun($file_path, $user_id . '.' . $ext);
                M('image')->add(['img_id' => $result['ImageId'], 'img_url' => $result['ImageURL']]);
                $final_avatar_path = $result['ImageURL'];
                // 删除本地文件
                unlink($file_path);
            } else {
                $final_avatar_path = 'avatar/' . $user_id . '.' . $ext;
                $this->user['avatar'] = $final_avatar_path;
            }

            $this->user['avatar'] = $final_avatar_path;
            $this->users_model->where(array("id" => $user_id))->save($this->user);
            sp_update_current_user($this->user);
            $re = array('status' => 1, 'data' => sp_get_user_avatar_url($final_avatar_path) . '?t=' . time());
            $this->ajaxReturn($re);
        } else {
            $this->error('头像更新失败');
        }
	}

	// 移动端我的收藏
    public function mobile_self_collect()
    {
        $type_limit = array(
            '0' => PostsModel::POST_TYPE_ARTICLE,
            '1' => PostsModel::POST_TYPE_DISCUSSION_QUESTION,
        );
        $index = I('index', 0, 'intval');
        if (array_key_exists($index, $type_limit)) {

            $this->assign('index', $index);

            foreach ($type_limit as $k => $type) {
                $where = ['p.post_type' => $type, 'p.post_status' => PostsModel::POST_STATUS_NORMAL, 't.user_id' => sp_get_current_userid(), 't.type' => TypeLog::LOG_TYPE_ARTICLE_COLLECT];
                $count = M('type_log')
                    ->alias('t')
                    ->join('__POSTS__ p on p.id = t.item_id')
                    ->where($where)
                    ->count();
                $type_count[$k] = $count;
            }
            $this->assign('type_count', $type_count);

            $where  = ['p.post_type' => $type_limit[$index], 'p.post_status' => PostsModel::POST_STATUS_NORMAL, 't.user_id' => sp_get_current_userid(), 't.type' => TypeLog::LOG_TYPE_ARTICLE_COLLECT];
            $count  = $type_count[$index];
            $page   = $this->page($count, 10);
            $lists  = M('type_log')
                ->alias('t')
                ->join('__POSTS__ p on p.id = t.item_id')
                ->where($where)
                ->limit($page->firstRow , $page->listRows)
                ->field('p.*, (SELECT COUNT(*) FROM rx_posts WHERE question_id = p.id) as answer_count')
                ->order("t.time desc")
                ->select();

            $this->assign('lists', $lists);
            $this->assign("page", $page->show('default'));
            $this->assign('total_pages', ceil($count / 10));
            $this->display();
        }
	}

    public function save_user_company_info()
    {
        if (IS_POST) {
            $company = I('post.');
            if ($company['id']) {
                M('users')->where(['id' => $company['id']])->save($company);
                $user = M('users')->where(['id' => $company['id']])->find();
                sp_update_current_user($user);
                $this->assign($user);
            }
            $this->success('操作成功');
        } else {
            $user = sp_get_current_user();
            $this->assign($user);
            $this->display();
        }
	}
}